import { expenseBillInfo, expenseBillInvoiceAdd, expenseBillInvoiceDelete, expenseBillInvoiceList, expenseBillStandardInfo } from "@/services/chargingManage";
import UserSession from "@/UserSession";
import { getUuid } from "@/utils/utils";
import { Button, message, Modal, Table, Tabs, Upload } from "antd";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import BillTable from "./billTable";

class BillModal extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      visible:false,
      current:'-1',
      list:[],
      loading:false,
      total:0,
      id:null,
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
  }

  initModal = (id,current) => {
    this.setState({
      loading:true,
      visible:true,
      id
    },() => {
      this.setState({current},() => {
        this.getDetail()
      })
    })
  }

  getDetail = async () => {
    const { id,current } = this.state;
    if(current == 3){
      const res = await expenseBillInvoiceList({id})
      this.setState({list:res})
    }
  }

  onCancel = () => {
    this.setState({
      visible:false,
      current:'-1',
      list:[],
      loading:false,
      total:0,
      id:null
    })
  }

      /**
   * 上传图片前判断
   * @returns {*}
   */
      beforeUpload = file => {
        let b = /\.(png|jpg|gif)$/;
        let a = file.name.toLowerCase();
    
        const pig = b.test(a);
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;
    
        if (!pig) {
          if (!isLt2M) {
            message.error(formatMessage({ id: 'billModal.upload.error.size' }));
          } else {
            message.error(formatMessage({ id: 'billModal.upload.error.format' }));
          }
        } else {
          if (!isLt2M) {
            message.error(formatMessage({ id: 'billModal.upload.error.size' }));
          }
        }
        return isJPG && isLt2M && pig;
      };
  
        /**
     * 更换图片
     * @returns {*}
     */
    handleChangeImage = (info) => {
      if (info.file.status === 'done') {
        this.doSaveImg(info.file.response.url)
      }
    };

    doSaveImg = async (imgUrl) => {
      const res = await expenseBillInvoiceAdd({billId:this.state.id,imgUrl})
      this.getDetail()
    }

    deleteConfirm = id => {
      Modal.confirm({
        title:formatMessage({ id: 'billModal.confirm.deleteTitle' }),
        okText:formatMessage({ id: 'billModal.confirm.ok' }),
        okType:"danger",
        cancelText:formatMessage({ id: 'billModal.confirm.cancel' }),
        onOk:() => {
          this.doDelete(id)
        }
      })
    }

    doDelete = async id => {
      const res = await expenseBillInvoiceDelete({id})
      if(res.code === -1){return false}
      message.info(res.message)
      this.getDetail()
    }

  render(){
    const { visible,list,loading,current,id } = this.state;
    const isAdmin = UserSession.getCurrentUser().tenantId == 1 
    const columns1 = [
      {
        title:formatMessage({ id: 'billModal.columns.type' }),
        dataIndex:"name",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.resource' }),
        dataIndex:"resourceName",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.packageQuantity' }),
        dataIndex:"packageNum",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.overflowUsage' }),
        dataIndex:"overflowNum",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.usageQuantity' }),
        dataIndex:"realUseNum",
        width:100
      }
    ]
    const columns2 = [
      {
        title:formatMessage({ id: 'billModal.columns.type' }),
        dataIndex:"name",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.resource' }),
        dataIndex:"resourceName",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.usageQuantity' }),
        dataIndex:"realUseNum",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.packageQuantity' }),
        dataIndex:"packageNum",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.overflowQuantity' }),
        dataIndex:"overflowNum",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.standardUnitPrice' }),
        dataIndex:"standardPrice",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.overflowUnitPrice' }),
        dataIndex:"overflowPrice",
        width:100
      },
      // {
      //   title:"实际总费用",
      //   dataIndex:"allPrice",
      //   width:120
      // },
      // {
      //   title:"套餐总价",
      //   dataIndex:"packageAllPrice",
      //   width:100
      // },
      // {
      //   title:"优惠总价",
      //   dataIndex:"packageDiscountPrice",
      //   width:100
      // },
      // {
      //   title:"应付总费用",
      //   dataIndex:"realAllPrice",
      //   width:120
      // },
    ]
    const columns3 = [
      {
        title:formatMessage({ id: 'billModal.columns.expenseItem' }),
        dataIndex:"resourceName",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.originalPrice' }),
        dataIndex:"yuanjia",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.deduction' }),
        dataIndex:"jianmian",
        width:100
      },
      {
        title:formatMessage({ id: 'billModal.columns.actualPayable' }),
        dataIndex:"shijiyingfu",
        width:100
      }
    ]

    return (
      <Modal
        title={formatMessage({ id: 'billModal.title' })}
        visible={visible}
        onCancel={this.onCancel}
        footer={null}
        width={800}
        bodyStyle={{height:"calc(100vh - 100px)",overflowY:"auto"}}
        centered
      >
        <Tabs activeKey={current} onChange={activeKey => this.setState({current:activeKey},() => this.getDetail())}>
          <Tabs.TabPane tab={formatMessage({ id: 'billModal.tabs.bill' })} key={'2'}>
            {current == 2 ? <BillTable columns={columns3} current={current} rowId={id} /> : ''}
          </Tabs.TabPane>
          <Tabs.TabPane tab={formatMessage({ id: 'billModal.tabs.usageDetails' })} key={'0'}>
            {current == 0 ? <BillTable columns={columns1} current={current} rowId={id} /> : ''}
          </Tabs.TabPane>
          {
            isAdmin ? (
              <Tabs.TabPane tab={formatMessage({ id: 'billModal.tabs.invoiceRecords' })} key={'3'}>
                <Upload
                  name="file"
                  listType="picture"
                  className="avatar-uploader"
                  showUploadList={false}
                  action="/cloud/file/upload"
                  beforeUpload={this.beforeUpload}
                  onChange={this.handleChangeImage}
                  accept=".png,.jpg"
                >
                  <Button type="primary">{formatMessage({ id: 'billModal.button.upload' })}</Button>
                </Upload>
                <div style={{display:"flex",marginTop:10,flexWrap:"wrap",gap:"10px"}}>
                  {
                    list.map(item => {
                      return (
                        <div key={item.imgUrl}>
                          <img src={item.imgUrl} style={{width:80,height:40,marginBottom:10}} />
                          <div style={{textAlign:"center"}}>
                            <a href={item.imgUrl} target="_blank" style={{marginRight:8}}>{formatMessage({ id: 'billModal.button.download' })}</a>
                            <span style={{cursor:"pointer",color:"red"}} onClick={() => this.deleteConfirm(item.id)}>{formatMessage({ id: 'billModal.button.delete' })}</span>
                          </div>
                        </div>
                      )
                    })
                  }
                </div>
              </Tabs.TabPane>
            ) : ''
          }
          {
            isAdmin ? (
              <Tabs.TabPane tab={formatMessage({ id: 'billModal.tabs.standardBilling' })} key={'1'}>
                {current == 1 ? <BillTable columns={columns2} current={current} rowId={id} /> : ''}
              </Tabs.TabPane>
            ) : ''
          }
        </Tabs>
      </Modal>
    )
  }
}

export default BillModal